package com.jackrain.clouddata.sys.Listenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 消费云数据消息
 */
@Component("com.jackrain.clouddata.sys.Listenter.CustomerMessageProcess")
@Slf4j
public class CustomerMessageProcess implements MessageProcess {
    private static final Logger logger = LoggerFactory.getLogger(CustomerMessageProcess.class);
    public CustomerMessageProcess() {

    }

    @Override
    public void process(Object json, String tag) throws Exception{
        JSONArray paramArray = JSONObject.parseArray(JSON.toJSONString(json, new SerializerFeature[]{SerializerFeature.WriteNullStringAsEmpty}));
        JSONObject paramObject = paramArray.getJSONObject(0);
        String tableName = paramObject.getString("name");
        JSONArray valueArray = paramObject.getJSONArray("value");
        Integer ad_client_id = QueryEngine.getInstance().doQueryInt("SELECT AD_CLIENT_ID FROM OMS_TAG WHERE TAGNAME = ?", new Object[]{tag});
        if (null == ad_client_id || "".equals(ad_client_id)) {
            throw new NDSException("公司ID未找到!");
        }
        //更新或插入
        for (int i = 0; i < valueArray.size(); i++) {
            String selSql = "SELECT COUNT(1) FROM " + tableName + " WHERE CODE = ? AND AD_CLIENT_ID = " + ad_client_id;
            int count = QueryEngine.getInstance().doQueryInt(selSql, new Object[]{valueArray.getJSONObject(i).get("CODE")});
            List paramList = new ArrayList();
            Set<String> keySet = valueArray.getJSONObject(i).keySet();
            if (count > 0) {
                StringBuffer strBuf = new StringBuffer("UPDATE "+tableName+" SET ");
                paramList = new ArrayList();
                for (String key: keySet) {
                    strBuf.append(key+" = ? ,");
                    if (key.substring(key.length()-4,key.length()).equals("DATE")) {
                        paramList.add(TypeUtils.castToDate(valueArray.getJSONObject(i).get(key)));
                    }else if (null == valueArray.getJSONObject(i).get(key) || "".equals(valueArray.getJSONObject(i).get(key))) {
                        paramList.add("");
                    }else{
                        paramList.add(valueArray.getJSONObject(i).get(key));
                    }
                }
                strBuf = new StringBuffer(strBuf.substring(0,strBuf.length()-1));
                strBuf.append(" WHERE CODE = ? AND AD_CLIENT_ID = ?");
                paramList.add(valueArray.getJSONObject(i).get("CODE"));
                paramList.add(ad_client_id);
                QueryEngine.getInstance().executeUpdate(strBuf.toString(),paramList.toArray());
            }else{
                StringBuffer strBuf = new StringBuffer("INSERT INTO " + tableName + "(");
                for (String key: keySet) {
                    strBuf.append(key+",");
                    if (key.substring(key.length()-4,key.length()).equals("DATE")) {
                        paramList.add(TypeUtils.castToDate(valueArray.getJSONObject(i).get(key)));
                    }else if (null == valueArray.getJSONObject(i).get(key) || "".equals(valueArray.getJSONObject(i).get(key))) {
                        if (key.substring(key.length()-4,key.length()).equals("CODE")){
                            paramList.add("99999");
                        }else {
                            paramList.add("");
                        }
                    }else{
                        paramList.add(valueArray.getJSONObject(i).get(key));
                    }
                }
                strBuf.append("ID,AD_CLIENT_ID) VALUES(");
                for (int j = 0; j < keySet.size(); j++) {
                    strBuf.append("?,");
                }
                strBuf.append("?,?)");
                paramList.add(Tools.getSequence(tableName));
                paramList.add(ad_client_id);
                QueryEngine.getInstance().executeUpdate(strBuf.toString(),paramList.toArray());
            }
        }
    }
}